package com.study.scapp.info.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.study.scapp.info.common.CommonResult;
import com.study.scapp.info.pojo.InfoBusiness;
import com.study.scapp.info.service.InfoBusinessService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 商家
 * @author 1
 * @data 2023/5/27
 */
@RestController
@RequestMapping("/business")
public class InfoBusinessController {

    @Resource
    private InfoBusinessService infoBusinessService;

    /**
     * 商家新增
     * @param business
     * @return
     */
    @PostMapping("/add")
    public CommonResult addBusiness(@RequestParam Map<String, Object> business){
        JSONObject jsonObject = new JSONObject();
        jsonObject.putAll(business);
        InfoBusiness infoBusiness = jsonObject.toJavaObject(InfoBusiness.class);
        QueryWrapper<InfoBusiness> infoBusinessQueryWrapper = new QueryWrapper<>();
        infoBusinessQueryWrapper.eq("business_name",infoBusiness.getBusinessName());
        List<InfoBusiness> list = infoBusinessService.list(infoBusinessQueryWrapper);
        if (list.size()>=1){
            return CommonResult.failed("该商家已存在！");
        }
        infoBusinessService.save(infoBusiness);
        return CommonResult.success("新增商家成功！");
    }

    /**
     * 商家列表
     * @return
     */
    @GetMapping("/list")
    public CommonResult businessList(){

        List<InfoBusiness> list = infoBusinessService.list(new QueryWrapper<InfoBusiness>().orderByDesc("create_time"));
        return CommonResult.success(list);
    }

    /**
     * 根据id删除商家
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public CommonResult deleteBusiness(@PathVariable("id")Long id){
        boolean b = infoBusinessService.removeById(id);
        if (b){
            return CommonResult.success("删除成功！");
        }else {
            return CommonResult.failed("删除失败！");
        }
    }
}
